package com.example.demo.buessiness.user.services;

import com.example.demo.buessiness.user.interfaces.IUserService;
import com.example.demo.buessiness.user.model.dto.UserRequest;
import com.example.demo.buessiness.user.model.dto.UserResponse;
import com.example.demo.buessiness.user.model.po.User;
import com.example.demo.buessiness.user.repository.UserRepository;
import msa.common.exception.IDataStorageException;
import msa.common.model.DataTableVO;
import msa.common.model.PageModel;
import msa.common.model.ResultModel;
import msa.common.utils.DataTableConverter;
import msa.common.utils.IDGenerator;
import msa.common.utils.ResultModelUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.kafka.common.protocol.types.Field;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;


@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    UserRepository userRepository;


    @Transactional(rollbackFor = IDataStorageException.class)
    @Override
    public ResultModel addUser(UserRequest clientRequest) {
        clientRequest.setId(String.valueOf(IDGenerator.getSnowflakeId()));
        try{
            User clients = requestToPojo(clientRequest);
            userRepository.save(clients);

            return ResultModelUtils.getEdiSuccessInstance(true);

        }catch (Exception e){
            throw new IDataStorageException("添加异常",e);
        }


    }


    @Transactional(rollbackFor = IDataStorageException.class)
    @Override
    public ResultModel updateUser(UserRequest clientRequest) {
        try{
            User clients = requestToPojo(clientRequest);
            //userRepository.saveAndFlush(clients);
            userRepository.save(clients);
            return ResultModelUtils.getEdiSuccessInstance(true);

        }catch (Exception e){
            throw new IDataStorageException("更新异常",e);
        }
    }


    @Transactional(rollbackFor = IDataStorageException.class)
    @Override
    public ResultModel deleteUser(Long id) {
        try {
            userRepository.deleteById (id);
            return ResultModelUtils.getDelSuccessInstance (true);
        } catch (Exception e) {

            throw  new IDataStorageException ("删除异常",e);
        }
    }

    @Override
    public ResultModel findById(Long id) {
        User user = userRepository.findById(id).get();
        return ResultModelUtils.getSuccessInstance(pojoToResponse(user));
    }

    @Override
    public List<UserResponse> findAll() {
        List<User> clients = userRepository.findAllByOrderByIdAsc ();
        return pojoLisToResponseList (clients);
    }

    @Transactional(rollbackFor = IDataStorageException.class)
    @Override
    public void updateUsernameById(String username,Long id) {
        userRepository.updateUsernameById (username,id);
    }

    //登录验证
    @Transactional(rollbackFor = IDataStorageException.class)
    @Override
    public List<UserResponse> logByUsername(String username,String password) {
        List<User> clients = userRepository.logByUsername (username,password);
        return pojoLisToResponseList (clients);
    }

    //查询用户名
    @Transactional(rollbackFor = IDataStorageException.class)
    @Override
    public List<UserResponse> findByUsername(String username) {
        List<User> clients = userRepository.findByUsername (username);
        return pojoLisToResponseList (clients);
    }


    @Override
    public User requestToPojo(UserRequest userRequest) {
        User client = new User ();
        BeanUtils.copyProperties (userRequest,client);
        client.setId (Long.parseLong (userRequest.getId ()));
//        if (clientRequest.getTime ()!=null) {
//            client.setTime (DateUtils.convertTimeToDate (clientRequest.getTime ()));
//        }
        return client;
    }

    @Override
    public List requestListToPojoList(List<UserRequest> list) {
        return null;
    }

    /**
     * XX数据pojo转换为数据返回response
     *
     * @param o XX数据pojo类
     * @return clientResponse XX数据pojo类
     */
//    @Override
    public UserResponse pojoToResponse(Object o) {
        UserResponse clientResponse = new UserResponse();
        User client = (User) o;
        BeanUtils.copyProperties(client, clientResponse);
        clientResponse.setId(String.valueOf(client.getId()));
        return clientResponse;
    }

    @Override
    public List<UserResponse> pojoLisToResponseList(List list) {
        if (CollectionUtils.isEmpty (list)) {
            return new ArrayList<> ();
        }
        List<UserResponse> responses = new ArrayList<> ();
        list.stream ().filter (client->client!=null).forEach (client->{
            responses.add (pojoToResponse (client));
        });
        return responses;
    }


    /**
     *  分页
     * @return DataTableVO
     */
    @Override
    public DataTableVO page(PageModel pageModel) {
        UserRequest request = (UserRequest)pageModel.getSearchData ();
        Page<User> page = userRepository.findAll ((root, criteriaQuery, criteriaBuilder)-> {
            List<Predicate> predicates = new ArrayList<>();
            if (request.getAge ()!=null) {
                predicates.add (criteriaBuilder.equal (root.get ("age").as (Integer.class),request.getAge ()));
            }
            return criteriaQuery.where(predicates.toArray(new Predicate[predicates.size()])).orderBy (criteriaBuilder.asc (root.get ("time"))).getRestriction();
        },pageModel.getPageRequestInstance ());
        DataTableVO dataTableVO =  DataTableConverter.convert(page);
        List<User> clients = page.getContent ();
        dataTableVO.setData (pojoLisToResponseList (clients));
        return dataTableVO;
    }
}
